package com.alter.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.alter.auth.annotation.Authorization;
import com.alter.auth.annotation.CurrentUser;
import com.alter.auth.manager.TokenManager;
import com.alter.domain.UserInfo;
import com.alter.handler.SendMbCode;
import com.alter.service.UserInfoService;
import com.wordnik.swagger.annotations.ApiImplicitParam;
import com.wordnik.swagger.annotations.ApiImplicitParams;
import com.wordnik.swagger.annotations.ApiOperation;

/**
 * @描述: 
 * @作者: alter
 * @时间：2017-8-24 上午10:33:14
 */
@RestController
@RequestMapping("/user")
public class UserController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private UserInfoService userInfoService;
	
	@Autowired
    private TokenManager tokenManager;
	
	@Autowired
	private SendMbCode sendMbCode;
	
	
	@RequestMapping(value="/getVerifyCode", method = RequestMethod.POST)
	@ApiOperation(value = "获取验证码")
    public JSONObject getVerifyCode(@RequestParam("mobile") String mobile, HttpSession httpSession) {
		JSONObject data = new JSONObject();
		// 将认证码存入SESSION
        data = sendMbCode.getVerifyCode(mobile);
        if(data != null){
           httpSession.setAttribute("verify_code", data.get("data"));  
        }
		return data;
    }
	
	@RequestMapping(value="/check", method = RequestMethod.POST)
	@ApiOperation(value = "注册手机校验")
    public JSONObject checkData(@RequestParam("login_id") String loginId) {
		JSONObject data = new JSONObject();
		Assert.notNull(loginId, "手机号不能为空");
		if(StringUtils.isEmpty(loginId)){
			data.put("ret", -1002);
	    	data.put("msg", "手机号不能为空");
	    	data.put("data", "");
	    	return data;
		}
		UserInfo userInfo = userInfoService.getUserInfo(loginId);
		if(userInfo == null){
			data.put("ret", 1);
	    	data.put("msg", "success");
	    	data.put("data", "");
			return data;
		}
		data.put("ret", -1003);
    	data.put("msg", "该手机号已经注册");
    	data.put("data", "");
		return data;
    }
	
	@RequestMapping(value="/register", method = RequestMethod.POST)
	@ApiOperation(value = "注册")
    public JSONObject createUser(@RequestParam("mobile") String mobile, @RequestParam("psw") String psw, @RequestParam("mb_code") String mbCode, HttpSession httpSession) {
		JSONObject data = new JSONObject();
		data.put("data", "");
		data.put("ret", -1);
		//从session获取验证信息
		String verifyStr = (String) httpSession.getAttribute("verify_code");
		if(StringUtils.isEmpty(verifyStr)){
	    	data.put("msg", "请获取验证码");
			return data;
		}
		//获取服务器端短信的手机号码
        String sessionMobile = verifyStr.split("\\|")[0];
	    //获取服务器端短信验证码
	    String mobileTicket = verifyStr.split("\\|")[1];
	    if(!sessionMobile.equals(mobile)){
	    	data.put("msg", "请重新获取短信验证码");
            return data;
	    }
	    else if(StringUtils.isEmpty(mbCode) || !mbCode.equals(mobileTicket))
	    {
	    	data.put("msg", "短信验证码错误");
            return data;
	    }
	    long checkTime = new Date().getTime();
        //获取服务器端发送验证码时间与当前时间差
        float btTime = (checkTime - Long.valueOf(verifyStr.split("\\|")[2]))/(1000);
        double LIMIT_TIME = 60.0D;
        //如果超时验证不通过
        if(LIMIT_TIME<btTime){
            data.put("msg", "验证码过期，请重新获取");
            return data;
        }
		try {
			UserInfo userInfo = userInfoService.getUserInfo(mobile);
			if(userInfo != null){
				data.put("ret", -1003);
		    	data.put("msg", "该手机号已经注册");
		    	data.put("data", "");
				return data;
			}
			UserInfo user = new UserInfo();
			user.setPsw(psw);
			user.setLoginId(mobile);
			userInfoService.registerUser(user);
		} catch (Exception e) {
			logger.error("用户注册失败："+e);
			data.put("ret", -1004);
	    	data.put("msg", "用户注册失败");
	    	data.put("data", "");
			return data;
		}
		data.put("ret", 1);
    	data.put("msg", "注册成功");
    	data.put("data", "");
		return data;
    }
	
	@RequestMapping(value="/login", method = RequestMethod.POST)
	public JSONObject userLogin(@RequestParam("login_id") String loginId, @RequestParam("psw") String psw){
		JSONObject data = new JSONObject();
		try {
			data = userInfoService.userLogin(loginId, psw);
		} catch (Exception e) {
			logger.error("用户登录失败："+e);
			data.put("ret", -1007);
	    	data.put("msg", "登录失败");
	    	data.put("data", "");
			return data;
		}
		return data;
	}
	
	@RequestMapping(method = RequestMethod.DELETE)
	@Authorization
    @ApiOperation(value = "退出登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public JSONObject logout(@CurrentUser UserInfo userInfo) {
		JSONObject data = new JSONObject();
        tokenManager.deleteToken(userInfo.getId());
        data.put("ret", 1);
    	data.put("msg", "success");
    	data.put("data", "");
		return data;
    }
	
	@RequestMapping(value="/getUserInfo", method = RequestMethod.POST)
	@Authorization
    @ApiOperation(value = "获取用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
	public JSONObject getUserInfo(@CurrentUser UserInfo userInfo) {
		JSONObject data = new JSONObject();
		Map model = new HashMap();
		model.put("user_id", userInfo.getId());
		model.put("user_name", userInfo.getUserName());
		model.put("user_image", userInfo.getUserImage());
        data.put("ret", 1);
    	data.put("msg", "success");
    	data.put("data", model);
		return data;
    }
	
	
	
	
	
	
}
